package com.leyou.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Slf4j
public class CookieUtils {

    /**
     * 得到cookie的值，不编码
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName){
        return getCookieValue(request,cookieName,null);
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName,String charset){
        Cookie[] cookieList = request.getCookies();
        if(cookieList==null || cookieName==null ){
            return null;
        }
        String retValue =null;
        try{
            for(int i=0;i<cookieList.length;i++){
                if(cookieList[i].getName().equals(cookieName)){
                    if(charset!=null && charset.length()>0){
                        retValue = URLDecoder.decode(cookieList[i].getValue(),charset);
                    }else{
                        retValue=cookieList[i].getValue();
                    }
                    break;
                }
            }
        }catch (UnsupportedEncodingException e){
            log.error("Cookie Decode Error" ,e);
        }
        return  retValue;
    }


}
